/*
 * @LastEditors: gfge
 * @Date: 2019-04-22 13:14:47
 * @LastEditTime: 2019-09-10 16:30:03
 */

// 计算表达式的值
export let evil = fn => {
  var Fn = Function // 一个变量指向Function，防止有些前端编译工具报错
  return new Fn('return ' + fn)()
}

export const type = obj => {
  return Object.prototype.toString
    .call(obj)
    .slice(8, -1)
    .toLowerCase()
}
/*
正则表达式
 */
export const regExpRules = {
  numberLetterChinese: /^[a-zA-Z0-9\u4e00-\u9fa5]+$/, // 中文数字字母
  numberLetter: /^[0-9a-zA-Z]*$/, // 数字字母
  numberLetterLine: /^[0-9a-zA-Z_\-]*$/, // 数字字母下划线中划线
  positiveNumber: /^[1-9]\d*$/, // 正整数
  number: /^[0-9]*$/, // 数字
  // price: /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/, // 价格
  phone: /^([0-9]{3,4}-)?[0-9]{7,8}$/, // 固话
  mobile: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, // 手机号
  zip: /^[0-9]{6}$/, // 邮编
  price: /^\d{1,8}(\.\d{1,2})?$/, // 价格
  priceNegative: /^-?\d{1,8}(\.\d{1,2})?$/, // 价格，可为负
  invoicePrice: /^\d{1,8}(\.\d{1,6})?$/, // 价格
  url: /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/,
  email: /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/, // 邮箱
  // 常用中英文及标点符号，不允许表情符号和空格
  commonCharacter: /^[A-Za-z0-9_\u4e00-\u9fa5\"\'\,\，\.\。\！\!\?\？\-\—\_\<\>\%\;\‘\’\；\)\《\（\）\》\(\&\+\=\`\“\”\·\*\#\@\@\▪\の\]\[]+$/
}

export const extend = (target, source, extendKeyList = []) => {
  extendKeyList.forEach(item => {
    target[item] = source[item]
  })
  return target
}

export const formatTime = (val, fmt = 'yyyy-MM-dd hh:mm:ss') => {
  if (!val) return
  val = new Date(val)

  var o = {
    'M+': val.getMonth() + 1, //  月份
    'd+': val.getDate(), // 日
    'h+': val.getHours(), // 小时
    'm+': val.getMinutes(), // 分
    's+': val.getSeconds(), // 秒
    'q+': Math.floor((val.getMonth() + 3) / 3), // 季度
    S: val.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (val.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      )
    }
  }
  return fmt
}

// 当前月第一天
export const getCurrentMonthFirst = () => {
  // console.log('当前月第一天')
  var date = new Date()
  date.setDate(1)
  var month = parseInt(date.getMonth() + 1)
  var day = date.getDate()
  if (month < 10) {
    month = '0' + month
  }
  if (day < 10) {
    day = '0' + day
  }
  return date.getFullYear() + '-' + month + '-' + day
}

// 当前月最后一天
export const getCurrentMonthLast = () => {
  // console.log('当前月最后一天')
  var date = new Date()
  var currentMonth = date.getMonth()
  var nextMonth = ++currentMonth
  var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1)
  var oneDay = 1000 * 60 * 60 * 24
  var lastTime = new Date(nextMonthFirstDay - oneDay)
  var month = parseInt(lastTime.getMonth() + 1)
  var day = lastTime.getDate()
  if (month < 10) {
    month = '0' + month
  }
  if (day < 10) {
    day = '0' + day
  }
  return date.getFullYear() + '-' + month + '-' + day
}

export const deepClone = source => {
  let result
  let item
  let t = type(source)
  if (t === 'array') {
    result = []
    for (item of source) {
      result.push(deepClone(item))
    }
  } else if (t === 'object') {
    result = {}
    for (item in source) {
      result[item] = deepClone(source[item])
    }
  } else {
    result = source
  }
  return result
}

export const serialize = data => {
  const result = {}

  for (let item in data) {
    if (data.hasOwnProperty(item)) {
      // 空值不传
      if (data[item] === '' || data[item] === undefined) {
        continue
      }

      // 日期转换为时间戳
      if (data[item] instanceof Date) {
        result[item] = +data[item]
        continue
      }

      result[item] = data[item]
    }
  }

  return result
}

/**
 * 丢掉 ‘_’开头的参数
 * 并把 abc__list[]-》{a,b,c}(以逗号隔开)
 * 过滤空参数
 * zz_开始的为日期对象，处理为毫秒后，属性名去掉zz
 */
export const filterParam = pm => {
  let rsPm = {}
  for (let key in pm) {
    if (pm[key] && pm[key] !== '' && key !== 'total') {
      if (key.indexOf('__') > 0) {
        // 改用正则
        if (pm[key].length > 0) {
          // book__list =[1,2] ==> book='{1,2}';
          rsPm[key.substring(0, key.indexOf('__'))] = pm[key].join(',')
        }
      } else if (key.startsWith('_')) {
        continue
      } else if (key.startsWith('zz_')) {
        // zz开始的为日期对象，处理为毫秒后，属性名去掉zz
        rsPm[key.substring(3)] =
          typeof pm[key] === 'number' ? pm[key] : pm[key].getTime()
      } else {
        rsPm[key] = pm[key]
      }
      // delete pm[key]
    }
  }
  return rsPm
}

// 项目中一些公共方法
export let isEmpty = obj => {
  for (const el in obj) {
    return false
  }

  return true
}

// 项目中一些公共方法
export let hasEmpty = obj => {
  for (const el in obj) {
    if (obj[el] === 'undefined' || obj[el] === null || obj[el] === '') {
      return true
    }
  }
  return false
}

// 过滤调对象中的一些值为空的属性
export let filterObj = obj => {
  let newObj = {}
  for (const key in obj) {
    if (obj[key] === 'undefined' || obj[key] === null || obj[key] === '') {
      continue
    } else {
      newObj[key] = obj[key]
    }
  }
  return newObj
}
// 是否为formdata
export let isFormData = v => {
  return Object.prototype.toString.call(v) === '[object FormData]'
}

export let getRouterValue = route => {
  let value = ''
  if (route.query.src) {
    value = route.query.src
  } else {
    value = route.path
  }
  return value
}

export let getScreen = () => {
  var width = document.body.clientWidth
  if (width >= 1200) {
    return 3 // 大屏幕
  } else if (width >= 992) {
    return 2 // 中屏幕
  } else if (width >= 768) {
    return 1 // 小屏幕
  } else {
    return 0 // 超小屏幕
  }
}

/**
 * 判断路由是否相等
 */
export const diff = (obj1, obj2) => {
  delete obj1.close
  var o1 = obj1 instanceof Object
  var o2 = obj2 instanceof Object
  if (!o1 || !o2) {
    /*  判断不是对象  */
    return obj1 === obj2
  }

  if (Object.keys(obj1).length !== Object.keys(obj2).length) {
    return false
    // Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如：数组返回下表：let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
  }

  for (var attr in obj1) {
    var t1 = obj1[attr] instanceof Object
    var t2 = obj2[attr] instanceof Object
    if (t1 && t2) {
      return diff(obj1[attr], obj2[attr])
    } else if (obj1[attr] !== obj2[attr]) {
      return false
    }
  }
  return true
}

/**
 * 入参格式化去头去尾空格
 */
export const formatter = obj => {
  for (let key in obj) {
    if (typeof obj[key] === 'string') {
      obj[key] = obj[key].trim()
    }
  }
  return obj
}
